package com.he.interceptor;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.he.constant.CommonConstant;
import com.he.constant.PageConstant;
import com.he.utils.PageUtils;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.servlet.http.HttpServletRequest;
import java.util.Optional;

/**
 * @author He
 * @version 1.0
 * @Date 2023/9/17 22:31
 * @Desc 分页拦截器
 * 用于拦截请求中的分页参数,并将其设置到ThreadLocal中  用于后续的分页查询
 */
@Component
public class PageableInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) {

        String currentPage = request.getParameter(PageConstant.CURRENT);
        // 如果当前页为空,则设置默认值
        String pageSize = Optional.ofNullable(request.getParameter(PageConstant.SIZE)).orElse(PageConstant.DEFAULT_SIZE);
        if (StringUtils.hasText(currentPage)) {
            PageUtils.setCurrentPage(new Page<>(Long.parseLong(currentPage), Long.parseLong(pageSize)));
        }

        return true;
    }

    @Override
    public void afterCompletion(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler, Exception ex) {
        // 清除ThreadLocal中的分页参数
        PageUtils.remove();
    }

}
